import axios from 'axios'
import store from '../store'
// import router from '@/router'

import { updateTokenAPI } from '@/api/user'
import router from '../router'

const request = axios.create({
  baseURL: 'http://toutiao.itheima.net' // 基地址
})
// 添加请求拦截器
request.interceptors.request.use(config => {
  if (store.state.token) {
    config.headers.Authorization = `Bearer ${store.state.token}`
  } else {
    config.headers.Authorization = `Bearer ${store.state.refresh_token}`
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 添加响应拦截器
request.interceptors.response.use(resp => { // http以2xx或3xx开头，执行成功回调
  return resp.data
}, async error => {
  // refresh_token过期
  if (error.response.data.message === 'refresh_token失效') {
    store.commit('setToken', '')
    store.commit('refresh_token', '')
    // 跳转到登陆页面重新登录
    router.replace({
      path: '/login?from=' + router.currentRoute.path
    })
  }
  if (error.response.status === 401) {
    // 清空vuex中 token
    store.commit('setToken', '')

    const resp = await updateTokenAPI()
    console.log(resp)
    // 更新Vuex中的token
    store.commit('setToken', resp.data.token)
    return request(error.config)
  }
  return Promise.reject(error)
})

export default request
